<template>
  <view class="add-contact">
    <!-- 顶部搜索框 -->
    <view class="search-box">
      <view class="search-input-box">
        <wd-icon name="search" size="16px" color="#999" class="search-icon" />
        <input
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索宗亲姓名、ID或手机号"
          confirm-type="search"
          @confirm="handleSearch"
        />
      </view>
      <view v-if="searchKeyword" class="search-btn" @click="handleSearch">搜索</view>
    </view>

    <!-- 搜索结果 -->
    <view v-if="searchKeyword && isSearched" class="search-result">
      <view v-if="searchResults.length > 0">
        <view
          v-for="(result, index) in searchResults"
          :key="index"
          class="result-item"
          @click="viewContactDetail(result)"
        >
          <image
            class="result-avatar"
            :src="result.avatar || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png'"
            mode="aspectFill"
          />
          <view class="result-info">
            <view class="result-name">{{ result.name }}</view>
            <view class="result-desc">{{ result.relation }}</view>
          </view>
          <view
            class="add-btn"
            :class="{ 'added-btn': result.isAdded }"
            @click.stop="addContact(result)"
          >
            {{ result.isAdded ? "已添加" : "添加" }}
          </view>
        </view>
      </view>
      <view v-else class="empty-result">
        <image class="empty-image" src="/static/empty-search.png" mode="aspectFit" />
        <text class="empty-text">未找到相关宗亲</text>
      </view>
    </view>

    <!-- 添加方式 -->
    <view v-if="!searchKeyword || !isSearched" class="add-methods">
      <view class="section-title">添加方式</view>

      <!-- 扫一扫添加 -->
      <view class="add-method" @click="scanCode">
        <view class="method-icon scan-icon">
          <wd-icon name="scan" size="24px" color="#3B8DFF" />
        </view>
        <view class="method-content">
          <view class="method-title">扫一扫</view>
          <view class="method-desc">扫描宗亲二维码添加</view>
        </view>
        <wd-icon name="right" size="16px" color="#ccc" />
      </view>

      <!-- 手机号添加 -->
      <view class="add-method" @click="showPhoneSearch = true">
        <view class="method-icon phone-icon">
          <wd-icon name="phone" size="24px" color="#07c160" />
        </view>
        <view class="method-content">
          <view class="method-title">手机号</view>
          <view class="method-desc">通过手机号添加宗亲</view>
        </view>
        <wd-icon name="right" size="16px" color="#ccc" />
      </view>

      <!-- 宗族ID添加 -->
      <view class="add-method" @click="showIdSearch = true">
        <view class="method-icon id-icon">
          <wd-icon name="id-card" size="24px" color="#ff9900" />
        </view>
        <view class="method-content">
          <view class="method-title">宗族ID</view>
          <view class="method-desc">通过宗族ID添加宗亲</view>
        </view>
        <wd-icon name="right" size="16px" color="#ccc" />
      </view>
    </view>

    <!-- 我的二维码 -->
    <view class="my-qrcode">
      <view class="qrcode-title">我的二维码</view>
      <view class="qrcode-desc">扫一扫下方二维码，添加我为宗亲</view>
      <view class="qrcode-container">
        <image v-if="qrcodeImage" class="qrcode-image" :src="qrcodeImage" mode="aspectFit" />
        <view v-else class="qrcode-loading">
          <wd-loading size="20px" color="#3B8DFF" />
          <text>生成中...</text>
        </view>
      </view>
      <button class="share-btn" :disabled="!qrcodeImage" @click="shareQrCode">
        <wd-icon name="share" size="16px" color="#fff" />
        分享我的二维码
      </button>
    </view>

    <!-- 手机号搜索弹窗 -->
    <view v-if="showPhoneSearch" class="modal">
      <view class="modal-mask" @click="showPhoneSearch = false"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">手机号搜索</text>
          <view class="modal-close" @click="showPhoneSearch = false">
            <wd-icon name="close" size="18px" color="#999" />
          </view>
        </view>
        <view class="modal-body">
          <input
            v-model="phoneNumber"
            class="modal-input"
            type="number"
            maxlength="11"
            placeholder="请输入手机号码"
          />
          <button class="modal-btn" @click="searchByPhone">搜索</button>
        </view>
      </view>
    </view>

    <!-- ID搜索弹窗 -->
    <view v-if="showIdSearch" class="modal">
      <view class="modal-mask" @click="showIdSearch = false"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">宗族ID搜索</text>
          <view class="modal-close" @click="showIdSearch = false">
            <wd-icon name="close" size="18px" color="#999" />
          </view>
        </view>
        <view class="modal-body">
          <input v-model="genealogyId" class="modal-input" type="text" placeholder="请输入宗族ID" />
          <button class="modal-btn" @click="searchById">搜索</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useUserStore } from "@/store/modules/user";
import QRCode from "qrcode";

// 定义联系人类型
interface ContactResult {
  id: string;
  name: string;
  avatar: string;
  relation: string;
  isAdded: boolean;
}

// 设置页面标题
uni.setNavigationBarTitle({
  title: "添加联系人",
});

// 搜索相关
const searchKeyword = ref("");
const isSearched = ref(false);
const searchResults = ref<ContactResult[]>([]);

// 模态框控制
const showPhoneSearch = ref(false);
const showIdSearch = ref(false);

// 搜索参数
const phoneNumber = ref("");
const genealogyId = ref("");

// 二维码相关
const qrcodeImage = ref<string>("");
const userStore = useUserStore();

// 生成用户二维码
const generateUserQRCode = async () => {
  try {
    // 获取用户信息
    const userInfo = userStore.userInfo;
    const userId = userInfo?.userId;

    if (!userId) {
      console.error("获取用户信息失败");
      return;
    }

    // 生成包含用户ID的分享链接
    const shareUrl = `${window.location.origin}/?userId=${userId}&action=addContact`;

    // 显示加载状态
    qrcodeImage.value = "";

    // 生成二维码
    if (typeof document !== "undefined") {
      // H5环境
      const canvas = document.createElement("canvas");
      await QRCode.toCanvas(canvas, shareUrl, {
        width: 120,
        margin: 1,
        color: {
          dark: "#333333",
          light: "#ffffff",
        },
      });
      qrcodeImage.value = canvas.toDataURL("image/png");
    } else {
      // 小程序环境
      qrcodeImage.value = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(shareUrl)}`;
    }
  } catch (error) {
    console.error("生成二维码失败:", error);
    // 降级方案
    const userInfo = userStore.userInfo;
    const userId = userInfo?.userId || "unknown";
    const shareUrl = `${window.location.origin}/?userId=${userId}&action=addContact`;
    qrcodeImage.value = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(shareUrl)}`;
  }
};

// 页面加载时生成二维码
onMounted(() => {
  generateUserQRCode();
});

// 搜索联系人
function handleSearch() {
  if (!searchKeyword.value.trim()) return;

  // 模拟搜索请求
  setTimeout(() => {
    // 模拟搜索结果
    searchResults.value = [
      {
        id: "1",
        name: "李家大姐",
        avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
        relation: "四代孙女",
        isAdded: false,
      },
      {
        id: "2",
        name: "李小妹",
        avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
        relation: "五代孙女",
        isAdded: true,
      },
    ];

    isSearched.value = true;
  }, 500);
}

// 扫描二维码
function scanCode() {
  uni.scanCode({
    success: (res) => {
      console.log("扫码结果：", res);
      uni.showToast({
        title: "扫码成功",
        icon: "success",
      });

      // 模拟添加成功
      setTimeout(() => {
        // 实际项目中应该解析二维码内容并查询用户信息
        searchResults.value = [
          {
            id: "3",
            name: "李二狗",
            avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
            relation: "六代孙",
            isAdded: false,
          },
        ];

        searchKeyword.value = "扫码结果";
        isSearched.value = true;
      }, 500);
    },
    fail: () => {
      uni.showToast({
        title: "扫码失败",
        icon: "none",
      });
    },
  });
}

// 通过手机号搜索
function searchByPhone() {
  if (!phoneNumber.value || phoneNumber.value.length !== 11) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
    });
    return;
  }

  // 模拟搜索
  uni.showLoading({ title: "搜索中..." });

  setTimeout(() => {
    uni.hideLoading();
    showPhoneSearch.value = false;

    // 模拟搜索结果
    searchResults.value = [
      {
        id: "4",
        name: "李大壮",
        avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
        relation: "五代孙",
        isAdded: false,
      },
    ];

    searchKeyword.value = phoneNumber.value;
    isSearched.value = true;
  }, 1000);
}

// 通过ID搜索
function searchById() {
  if (!genealogyId.value) {
    uni.showToast({
      title: "请输入宗族ID",
      icon: "none",
    });
    return;
  }

  // 模拟搜索
  uni.showLoading({ title: "搜索中..." });

  setTimeout(() => {
    uni.hideLoading();
    showIdSearch.value = false;

    // 模拟搜索结果
    searchResults.value = [
      {
        id: "5",
        name: "李志强",
        avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png",
        relation: "七代孙",
        isAdded: false,
      },
    ];

    searchKeyword.value = genealogyId.value;
    isSearched.value = true;
  }, 1000);
}

// 添加联系人
function addContact(contact: ContactResult) {
  if (contact.isAdded) return;

  uni.showLoading({ title: "添加中..." });

  setTimeout(() => {
    uni.hideLoading();

    // 更新联系人状态
    contact.isAdded = true;

    uni.showToast({
      title: "添加成功",
      icon: "success",
    });
  }, 800);
}

// 查看联系人详情
function viewContactDetail(contact: ContactResult) {
  if (!contact.isAdded) {
    return;
  }

  // uni.navigateTo({
  //   url: `/pages/chat/contact-detail?name=${encodeURIComponent(contact.name)}`,
  // });
}

// 分享二维码
function shareQrCode() {
  if (!qrcodeImage.value) return;

  // 显示分享菜单
  uni.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage", "shareTimeline"],
  });
}

// 监听分享
uni.onShareAppMessage(() => {
  return {
    title: "添加我为宗亲",
    path: `/?userId=${userStore.userInfo?.userId || "unknown"}&action=addContact`,
    imageUrl: qrcodeImage.value || "/static/qrcode.png",
  };
});

uni.onShareTimeline(() => {
  return {
    title: "添加我为宗亲",
    query: `userId=${userStore.userInfo?.userId || "unknown"}&action=addContact`,
    imageUrl: qrcodeImage.value || "/static/qrcode.png",
  };
});
</script>

<style lang="scss">
.add-contact {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 50rpx;
}

.search-box {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
}

.search-input-box {
  display: flex;
  flex: 1;
  align-items: center;
  background-color: #f0f0f0;
  height: 72rpx;
  border-radius: 36rpx;
  padding: 0 30rpx;
}

.search-icon {
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 72rpx;
  line-height: 72rpx;
  font-size: 28rpx;
  background-color: transparent;
}

.search-btn {
  padding: 0 30rpx;
  font-size: 28rpx;
  color: #3b8dff;
}

.search-result {
  background-color: #fff;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.result-avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.result-info {
  flex: 1;
}

.result-name {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.result-desc {
  font-size: 24rpx;
  color: #999;
}

.add-btn {
  padding: 10rpx 30rpx;
  background-color: #3b8dff;
  color: #fff;
  font-size: 26rpx;
  border-radius: 30rpx;
}

.added-btn {
  background-color: #ccc;
}

.empty-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.add-methods {
  margin-top: 20rpx;
  background-color: #fff;
}

.section-title {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #999;
}

.add-method {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.method-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.scan-icon {
  background-color: rgba(59, 141, 255, 0.1);
}

.phone-icon {
  background-color: rgba(7, 193, 96, 0.1);
}

.id-icon {
  background-color: rgba(255, 153, 0, 0.1);
}

.method-content {
  flex: 1;
}

.method-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.method-desc {
  font-size: 24rpx;
  color: #999;
}

.my-qrcode {
  margin-top: 40rpx;
  padding: 40rpx 30rpx;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qrcode-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 10rpx;
}

.qrcode-desc {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.qrcode-container {
  padding: 30rpx;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400rpx;
}

.qrcode-image {
  width: 400rpx;
  height: 400rpx;
}

.qrcode-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.qrcode-loading text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

.share-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #3b8dff;
  color: #fff;
  font-size: 28rpx;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  line-height: 1;

  .wd-icon {
    margin-right: 10rpx;
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  width: 80%;
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.modal-close {
  padding: 10rpx;
}

.modal-body {
  padding: 40rpx 30rpx;
}

.modal-input {
  height: 88rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  margin-bottom: 30rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.modal-btn {
  background-color: #3b8dff;
  color: #fff;
  font-size: 30rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
}
</style>
